package com.sanq.product.cab.es.factory;

import com.sanq.product.cab.es.config.Nodes;
import com.sanq.product.cab.tools.strings.StringUtil;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

/**
 * 配置ES链接
 * <p>
 * 官方地址
 * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-overview.html
 */
public class EsCluster implements FactoryBean<RestHighLevelClient>, InitializingBean, DisposableBean {

    private Nodes nodes;

    private RestHighLevelClient client;

    public EsCluster() {
    }

    public EsCluster(Nodes nodes) {
        this.nodes = nodes;
    }

    public Nodes getNodes() {
        return nodes;
    }

    public void setNodes(Nodes nodes) {
        this.nodes = nodes;
    }

    @Override
    public void destroy() throws Exception {
        if (this.client != null)
            client.close();
    }

    @Override
    public RestHighLevelClient getObject() throws Exception {
        return this.client;
    }

    @Override
    public Class<?> getObjectType() {
        return EsCluster.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        initClient();
    }

    private void initClient() {
        String nodesMsg = this.nodes.getNodes();

        String[] nodesArr = nodesMsg.split(",");

        HttpHost[] httpHostList = new HttpHost[nodesArr.length];

        for (int i = 0, size = nodesArr.length; i < size; i++) {
            String[] hp = nodesArr[i].split(":");
            httpHostList[i] = new HttpHost(hp[0], StringUtil.toInteger(hp[1]), "http");
        }

        client = new RestHighLevelClient(RestClient.builder(httpHostList));
    }
}
